package com.cloud.cloudvideo.shiro;

import java.security.Permissions;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.cloud.cloudvideo.entity.SysPermission;
import com.cloud.cloudvideo.entity.SysRolePermssionPo;
import com.cloud.cloudvideo.entity.SysUser;
import com.cloud.cloudvideo.entity.SysUserRoleInfoPo;
import com.cloud.cloudvideo.service.LoginService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private LoginService loginService;
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String uname = (String) principalCollection.getPrimaryPrincipal();
		 //查询用户名称
        SysUserRoleInfoPo userPojo = loginService.getUserByName(uname);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (SysRolePermssionPo role : userPojo.getRolelist()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getName());
            //添加权限
            for (SysPermission permissions : role.getPermissionlist()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPerms());
            }
        }
        return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
			return null;
		}
		// 获取用户信息
//		String name = authenticationToken.getPrincipal().toString();
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		SysUser user = loginService.getUserByName(token.getUsername());
		if (user == null) {
			// 这里返回后会报出对应异常
			return null;
		} else {
			// 这里验证authenticationToken和simpleAuthenticationInfo的信息
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,
					user.getPassword().toString(), getName());
			return simpleAuthenticationInfo;
		}
	}
}
